/*
 * Copyright (C) 2015 KNIGHT, Inc. All Rights Reserved.
 */
package com.dap.configuration.web.zookeeper.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baidu.disconf.core.common.constants.DisConfigTypeEnum;
import com.baidu.disconf.core.common.path.ZooPathMgr;
import com.baidu.disconf.core.common.zookeeper.ZookeeperMgr;
import com.baidu.disconf.web.innerapi.zookeeper.ZooKeeperDriver;
import com.baidu.disconf.web.service.zookeeper.config.ZooConfig;
import com.baidu.dsp.common.exception.RemoteException;
import com.dap.configuration.utils.ZooPathExtensionMgr;
import com.dap.configuration.web.zookeeper.ZooKeeperExtensionDriver;

/**
 * Created by dengxiang on 15/1/14.
 */
@Service
public class ZookeeperDriverExtensionImpl implements
		ZooKeeperExtensionDriver, InitializingBean, DisposableBean {

	private static final Logger LOG = LoggerFactory
			.getLogger(ZooKeeperDriver.class);

	@Autowired
	private ZooConfig zooConfig;

	// 是否初始化
	private static boolean isInit = false;

	/**
	 * 通知某个Node更新
	 *
	 * @param app
	 * @param env
	 * @param version
	 * @param disConfigTypeEnum
	 */
	@Override
	public void notifyNodeUpdate(String app, String env, String version,
			String key, String value, String bankKey,
			DisConfigTypeEnum disConfigTypeEnum) {

		// 获取路径
		String baseUrlString = ZooPathExtensionMgr.getZooBaseUrl(
				zooConfig.getZookeeperUrlPrefix(), app, env, version, bankKey);
		String path = "";
		if (disConfigTypeEnum.equals(DisConfigTypeEnum.ITEM)) {

			path = ZooPathMgr.getItemZooPath(baseUrlString);
		} else {
			path = ZooPathMgr.getFileZooPath(baseUrlString);
		}

		try {

			path = ZooPathMgr.joinPath(path, key);

			boolean isExist = ZookeeperMgr.getInstance().exists(path);
			if (!isExist) {

				LOG.info(path + " not exist. not update ZK.");

			} else {
				// 通知
				ZookeeperMgr.getInstance().writePersistentUrl(path, value);
			}

		} catch (Exception e) {

			LOG.error(e.toString(), e);
			throw new RemoteException("zk.notify.error", e);
		}
	}


	@Override
	public synchronized void afterPropertiesSet() throws Exception {

		if (!isInit) {

			ZookeeperMgr.getInstance().init(zooConfig.getZooHosts(),
					zooConfig.getZookeeperUrlPrefix(), false);
			isInit = true;
		}
	}

	@Override
	public void destroy() throws Exception {
		
	}
}
